package com.fuhao.pay.stragety.impl;

import com.fuhao.core.utils.HttpClient;
import com.fuhao.core.utils.SpringContextUtil;
import com.fuhao.dto.output.PayMentTransacDTO;
import com.fuhao.pay.entity.PaymentChannelEntity;
import com.fuhao.pay.stragety.PayStrategy;
import com.fuhao.wx.WxProperties;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhang
 * @title: 微信扫码支付
 */
@Component
@Slf4j
public class WxPayStrategy implements PayStrategy {

//    @Autowired
//    private WxProperties wxProperties;

    @Override
    public String toPayHtml(PaymentChannelEntity paymentChannelEntity, PayMentTransacDTO payMentTransacDTO) {
        WxProperties wxProperties = (WxProperties) SpringContextUtil.getBean("wxProperties");
        //1.参数封装
        Map param=new HashMap();
        param.put("appid", wxProperties.getAppID());//公众账号ID
        param.put("mch_id", wxProperties.getMchID());//商户
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
        param.put("body", "苹果7p");
        String paymentId = payMentTransacDTO.getPaymentId();
        param.put("out_trade_no",paymentId);//交易订单号
        Long payAmount = payMentTransacDTO.getPayAmount();
        param.put("total_fee", payAmount+"");//金额（分）
        param.put("spbill_create_ip", "127.0.0.1");
        param.put("notify_url", wxProperties.getNotifyUrl());
        param.put("trade_type", "NATIVE");//交易类型

        try {
            String xmlParam = WXPayUtil.generateSignedXml(param,wxProperties.getKey());
            System.out.println("请求的参数："+xmlParam);

            //2.发送请求
            HttpClient httpClient=new HttpClient(wxProperties.getUnifiedorder());
            httpClient.setHttps(true);
            httpClient.setXmlParam(xmlParam);
            httpClient.post();

            //3.获取结果
            String xmlResult = httpClient.getContent();

            Map<String, String> mapResult = WXPayUtil.xmlToMap(xmlResult);
            System.out.println("微信返回结果"+mapResult);
//            Map map=new HashMap<>();
//            map.put("code_url", );//生成支付二维码的链接
//            map.put("out_trade_no", paymentId);
//            map.put("total_fee", payAmount+"");
//            JsonObject

            return mapResult.get("code_url");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}
